package com.gcsoftware.web.controller;

import com.gcsoftware.utils.SysConst;
import com.gcsoftware.utils.TokenUtils;
import com.gcsoftware.web.beans.T_GW_APPS;
import com.gcsoftware.web.beans.T_GW_APP_IPS;
import com.gcsoftware.web.beans.response.GetTokenRsp;
import com.gcsoftware.web.service.T_GW_APPS_SERVICE;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by qs on 2018/4/14.
 */
@RestController
@RequestMapping("")
public class TokenController {


    @Autowired
    private T_GW_APPS_SERVICE appService;


    @GetMapping("/getToken")
    public GetTokenRsp getTokenGet(HttpServletRequest request) {
        String appId = request.getParameter("app_id");
        String secret = request.getParameter("access_secret");
        return getToken(appId,secret);
    }
    public GetTokenRsp getToken(String appId, String secret) {
        GetTokenRsp rsp = new GetTokenRsp();
        if (StringUtils.isBlank(appId)) {
            rsp.setErrCode(TokenUtils.UNFOUND_APP_ID);
            rsp.setErrMsg("缺少app_id参数");
            return rsp;
        }
        if (StringUtils.isBlank(secret)) {
            rsp.setErrCode(TokenUtils.UNFOUND_APP_SECRET);
            rsp.setErrMsg("缺少access_secret参数");
            return rsp;
        }
        T_GW_APPS app = appService.getById(appId);
        if (null == app) {
            rsp.setErrCode(TokenUtils.INVALID_APP_ID);
            rsp.setErrMsg("不合法的 app_id ，请开发者检查 appId 的正确性");
            return rsp;
        }
        if (!secret.equals(app.getC_PASSWORD())) {
            rsp.setErrCode(TokenUtils.INVALID_APP_SECRET);
            rsp.setErrMsg("access_secret错误！");
            return rsp;
        }

        if (SysConst.DICT_APP_STATUS_OFFLINE.equals(app.getC_APP_STATUS())) {
            rsp.setErrCode(TokenUtils.INVALID_APP_ID);
            rsp.setErrMsg("不合法的 app_id ，请开发者检查 appId 的正确性");
            return rsp;
        }
        List<T_GW_APP_IPS> appIps = appService.queryForIpList(appId);
        List<String> ips = null;
        if (CollectionUtils.isNotEmpty(appIps)) {
            ips = new ArrayList<>();
            for (T_GW_APP_IPS ip: appIps) {
                ips.add(ip.getC_APP_IP());
            }
        }
        return TokenUtils.generateToken(app,ips);
    }

    @PostMapping("/getToken")
    public GetTokenRsp getTokenPost(String app_id, String access_secret) {
        return getToken(app_id,access_secret);
    }
}
